package com.hmyd.hmyd_android.shop;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.AppSystem;
import com.hmyd.hmyd_android.dto.JfMallBannerDto;
import com.hmyd.hmyd_android.dto.SystemMall;
import com.hmyd.hmyd_android.dto.myenum.JfMallEnum;
import com.hmyd.hmyd_android.dto.myenum.JfMallSortEnum;
import com.hmyd.hmyd_android.easydialog.EasyDialog;
import com.hmyd.hmyd_android.ui.BasicFragmentActivity;
import com.hmyd.hmyd_android.ui.LoginActivity;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.SelectedPopWindow;
import com.hmyd.hmyd_android.view.ad.AutoGallery;
import com.hmyd.hmyd_android.view.ad.AutoGalleryAdapter;
import com.hmyd.hmyd_android.view.ad.AutoGalleryBase;
import com.hmyd.hmyd_android.weigets.AbstractSpinnerAdapter.IOnItemSelectListener;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

@ContentView(R.layout.activity_jf_mall)
public class JfMallActivity extends BasicFragmentActivity {

	private static final int GET_JFMALL_BANNER = 1001;
	private static final int JFMALL_SETTING = 1002;

	private Context mContext;

	private String[] categorys = { "实物商品", "虚拟商品" };

	private String sort = JfMallSortEnum.MDEFAULT; // 全局排序方式
	private String category = JfMallEnum.GOODS;// 全局类别选择

	private List<JfMallBannerDto> mBanner = new ArrayList<JfMallBannerDto>(); // 存储banner信息
	private ArrayList<AutoGalleryBase> mAutoGalleryBases = new ArrayList<AutoGalleryBase>();
	private AutoGalleryAdapter mAutoGalleryAdaoter;

	private PhysicalGoodsFragment physicalGoodsFragment; // 真实货物
	private VirtualGoodsFragment virtualGoodsFragment; // 虚拟货物

	private List<Fragment> fragments;
	private FragmentPagerAdapter fragmentAdapter;

	@ViewInject(R.id.home_layout)
	private View home_title;
	@ViewInject(R.id.home_left)
	private ImageView jfmallBack; // 返回
	@ViewInject(R.id.home_title_txt)
	private TextView jfmallLabel; // 标题
	@ViewInject(R.id.home_right)
	private TextView mJfmallBtn; // 我的积分商城
	@ViewInject(R.id.JfMall_banner)
	private AutoGallery adBanner; // 循环banner
	@ViewInject(R.id.item_category_spinner)
	private Button categorySpinner; // 类型选择器
	@ViewInject(R.id.item_category_spinner_parent)
	private RelativeLayout item_category_spinner_parent;// 类型选择器父容器
	@ViewInject(R.id.item_price_spinner)
	private CheckBox priceSpiner; // 价格排序
	@ViewInject(R.id.item_new_spinner)
	private CheckBox newSpinner; // 最新排序
//	@ViewInject(R.id.item_hot_spinner)
//	private CheckBox hotSpinner; // 热度排序
	@ViewInject(R.id.my_shoping_cart)
	private ImageView shopCart; // 购物车
	@ViewInject(R.id.go_top)
	private ImageView backTopBtn; // 返回顶部
	@ViewInject(R.id.JfMall_banner_father)
	private View view;
	@ViewInject(R.id.JfMall_viewPager)
	private ViewPager JfMall_viewPager;
	@ViewInject(R.id.exchange_hot)
	private View exchange_hot;

	private EasyDialog dialog;
	private SelectedPopWindow popWindow;
	private boolean popWindowIsShow = false;

	@OnClick({ R.id.my_shoping_cart, R.id.go_top, R.id.item_price_spinner,
			R.id.item_category_spinner, R.id.exchange_hot })
	public void click(View view) {
		Intent intent = new Intent();
		switch (view.getId()) {
		case R.id.my_shoping_cart:
			intent.setClass(JfMallActivity.this, JfMallShopCartActivity.class); // 购物车
			startActivity(intent);
			break;
		case R.id.go_top:
			Intent intent1 = new Intent();
			if (physicalGoodsFragment.getUserVisibleHint()) {
				intent1.setAction("topG");
			} else if (virtualGoodsFragment.getUserVisibleHint()) {
				intent1.setAction("topV");
			}
			sendBroadcast(intent1);
			break;
		case R.id.item_category_spinner:
			// 判断系统版本，大于10用easydailog，否则用popwindow
			if (Integer.parseInt(android.os.Build.VERSION.SDK) > 10) {
				if (popWindowIsShow) {
					dialog.dismiss();
					popWindowIsShow = false;
				} else {
					showCategorySpinner();
					popWindowIsShow = true;
				}
			} else {
				if (popWindowIsShow) {
					popWindow.dismiss();
					popWindowIsShow = false;
				} else {
					showPopWindow();
					popWindowIsShow = true;
				}
			}

			break;
		// case R.id.item_new_spinner: // 最新排序
		// // Intent intent3 = new Intent();
		// // intent3.setAction("newSort");
		// // if (priceSpiner.isChecked()) {
		// // sort = JfMallSortEnum.PRICEDESCENDING;
		// // } else {
		// // sort = JfMallSortEnum.PRICEASCENDING;
		// // }
		// // intent3.putExtra("isNewSort", newSpinner.isChecked());
		// // mContext.sendBroadcast(intent3);
		// // priceSpiner.setChecked(false);
		// // hotSpinner.setChecked(false);
		// break;
		case R.id.exchange_hot: // 最热排序
			if (AppBasic.isLogin) {
				if (AppBasic.appMall != null && !TextUtils.isEmpty(AppBasic.appMall.exAddress)) {
					Utils.jumpURL(this, AppBasic.appMall.exAddress, "兑奖专区", "", false);
				} else {
					onRequest(JFMALL_SETTING, UrlConstant.JFMALL_SETTING, HttpMethod.GET, null);
				}
			} else {
				intent.setClass(JfMallActivity.this, LoginActivity.class);
				startActivity(intent);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 添加 Home Title 触摸监听事件（必须要添加在子类中）
	 */
	protected OnTouchListener touch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int X = (int) event.getX();
			if (X < Utils.screenWidth_ / 5) {
				leftButton();
			} else if (X > Utils.screenWidth_ * 4 / 5) {
				rightButton();
			}
			return false;
		}
	};
	
	private OnPageChangeListener fragmentPageChangeListener = new OnPageChangeListener() {
		
		@Override
		public void onPageSelected(int position) {
			categorySpinner.setText(categorys[position]);
			category = categorys[position];
		}
		
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			
		}
		
		@Override
		public void onPageScrollStateChanged(int arg0) {
			
		}
	};

	/**
	 * Home Title 左侧触摸事件调用方法
	 */
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	};

	/**
	 * Home Title 右侧触摸事件调用方法
	 */
	protected void rightButton() {
		Intent intent = new Intent();
		if (AppBasic.isLogin) {
			intent.setClass(JfMallActivity.this, JfMallMyActivity.class); // 我的积分商城
		} else {
			intent.setClass(JfMallActivity.this, LoginActivity.class);
		}
		startActivity(intent);
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
	}

	private void initData() {
		mContext = this;
		jfmallLabel.setText("积分商城");
		mJfmallBtn.setBackgroundResource(R.drawable.ji_icon_ger);
		home_title.setOnTouchListener(touch);

		ViewGroup.LayoutParams galleryParams = view.getLayoutParams();
		galleryParams.height = (int) ((float) Utils.screenWidth_ * 110f / 375f); // gallery控件宽高比位375:110
		galleryParams.width = Utils.screenWidth_;
		view.setLayoutParams(galleryParams);

		fragments = new ArrayList<Fragment>();
		physicalGoodsFragment = new PhysicalGoodsFragment();
		virtualGoodsFragment = new VirtualGoodsFragment();
		fragments.add(physicalGoodsFragment);
		fragments.add(virtualGoodsFragment);
		fragmentAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

			@Override
			public int getCount() {
				return fragments.size();
			}

			@Override
			public Fragment getItem(int arg0) {
				return fragments.get(arg0);
			}
		};
		JfMall_viewPager.setAdapter(fragmentAdapter);
		categorySpinner.setText(categorys[0]); // 初始停留在实物界面
		JfMall_viewPager.setOnPageChangeListener(fragmentPageChangeListener);
		if (Integer.parseInt(android.os.Build.VERSION.SDK) <= 10) {
			initPopWindow();
		}
		mAutoGalleryAdaoter = new AutoGalleryAdapter(JfMallActivity.this,
				adBanner, mAutoGalleryBases);
		adBanner.getItemLayout();
		adBanner.setAdapter(mAutoGalleryAdaoter);
		adBanner.initPointView(JfMallActivity.this, view);
		adBanner.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String idString = mBanner.get(position).id;
				Intent intent = new Intent();
				intent.setClass(JfMallActivity.this, GoodsDetailsActivity.class);
				intent.putExtra("id", idString);
				startActivity(intent);
			}
		});

		adBanner.setFocusable(true);

		newSpinner.setOnCheckedChangeListener(checkListener);
		priceSpiner.setOnCheckedChangeListener(checkListener);
		onRequest(GET_JFMALL_BANNER, UrlConstant.JFMALL_BANNER, HttpMethod.GET,
				null); // 请求banner
	}

	@Override
	public void onPostSuccess(int postId, String msg) {
		Gson gson = new Gson();
		Type type = null;
		switch (postId) {
		case GET_JFMALL_BANNER:
			type = new TypeToken<List<JfMallBannerDto>>() {
			}.getType();
			if (!TextUtils.isEmpty(msg)) {
				mBanner.clear();
				mBanner = gson.fromJson(msg, type);
				refreshBanner();
			}
			break;
		case JFMALL_SETTING:
			type = new TypeToken<SystemMall>() {}.getType();
			SystemMall system = gson.fromJson(msg, type);
			if (system != null && system.sys != null && system.sys.app != null) {
				AppBasic.appMall = system.sys.app;
			}
			
			if (AppBasic.appMall != null && !TextUtils.isEmpty(AppBasic.appMall.exAddress)) {
				Utils.jumpURL(this, AppBasic.appMall.exAddress, "兑换专区", "", false);
			}
			break;
		default:
			break;
		}
	}

	private OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			Intent intent2 = new Intent();
			intent2.setAction("sort");
			if (isChecked) {
				sort = JfMallSortEnum.PRICEDESCENDING;
			} else {
				sort = JfMallSortEnum.PRICEASCENDING;
			}
			if (physicalGoodsFragment.getUserVisibleHint()) {
				category = JfMallEnum.GOODS;
			} else {
				category = JfMallEnum.VIRTUAL;
			}
			intent2.putExtra("sort", sort);
			intent2.putExtra("category", category);
			mContext.sendBroadcast(intent2);
			if (priceSpiner.isChecked()) {
				newSpinner.setChecked(false);
			} else if (newSpinner.isChecked()) {
				priceSpiner.setChecked(false);
			}
		}
	};

	/*private OnCheckedChangeListener hotCheckChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			Intent intent2 = new Intent();
			intent2.setAction("sort");
			if (isChecked) {
				sort = JfMallSortEnum.MDEFAULT;
			}
			if (physicalGoodsFragment.getUserVisibleHint()) {
				category = JfMallEnum.GOODS;
			} else {
				category = JfMallEnum.VIRTUAL;
			}
			intent2.putExtra("sort", sort);
			intent2.putExtra("category", category);
			mContext.sendBroadcast(intent2);
			newSpinner.setChecked(false);
			priceSpiner.setChecked(false);
		}
	};*/

	private OnItemClickListener categoryClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			switch (position) {
			case 0:
				category = JfMallEnum.GOODS;
				JfMall_viewPager.setCurrentItem(0, false);
				break;
			case 1:
				categorySpinner.setText(JfMallEnum.VIRTUAL);
				category = JfMallEnum.VIRTUAL;
				JfMall_viewPager.setCurrentItem(1, false);
				break;
			default:
				break;
			}
			dialog.dismiss();
			categorySpinner.setText(categorys[position]);
		}
	};

	private void refreshBanner() {
		if (mBanner != null && mBanner.size() > 0) {
			mAutoGalleryBases.clear();
			for (JfMallBannerDto dto : mBanner) {
				AutoGalleryBase autogallery = new AutoGalleryBase();
				autogallery.mUrl = dto.icon;
				autogallery.mTitle = dto.title;
				mAutoGalleryBases.add(autogallery);
			}
			adBanner.setAdapter(mAutoGalleryAdaoter);
			mAutoGalleryAdaoter.notifyDataSetChanged();
		} else {
			Log.d("JfMallActivity", "get banner failed");
		}
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		switch (postId) {
		case GET_JFMALL_BANNER:
			MyToast.showHMToast(JfMallActivity.this, false, "服务器异常!"
					+ GET_JFMALL_BANNER);
			break;
		default:
			break;
		}
	}

	private void showCategorySpinner() {
		View root = LayoutInflater.from(this).inflate(
				R.layout.view_mpopwindow_listview, null);
		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(
				JfMallActivity.this, R.layout.view_jfmall_spinner_item,
				categorys);
		ListView lv = (ListView) root.findViewById(R.id.mListView);
		lv.setAdapter(categoryAdapter);
		lv.setOnItemClickListener(categoryClickListener);

		dialog = new EasyDialog(this).setLayout(root)
				// 设置布局文件
				.setBackgroundColor(getResources().getColor(R.color.tran))
				// 设置布局背景
				.setLocationByAttachedView(categorySpinner)
				// 设置显示位置
				.setTouchOutsideDismiss(true)
				// 设置触摸外部是否取消
				.setMatchParent(false)
				// 设置是否填充
				.setMarginLeftAndRight(2, 0)
				// 距离屏幕位置
				.setOutsideColor(Color.TRANSPARENT).setMarginLeftAndRight(0, 0)
				.show(); // 设置对话框外部背景颜色
	}

	private void initPopWindow() {
		popWindow = new SelectedPopWindow(mContext);
		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(
				JfMallActivity.this, R.layout.view_jfmall_spinner_item,
				categorys);
		popWindow.setAdapter(categoryAdapter);
		popWindow.setItemListener(new IOnItemSelectListener() {

			@Override
			public void onItemClick(int pos) {
				switch (pos) {
				case 0:
					category = JfMallEnum.GOODS;
					JfMall_viewPager.setCurrentItem(0, false);
					break;
				case 1:
					category = JfMallEnum.VIRTUAL;
					JfMall_viewPager.setCurrentItem(1, false);
					break;
				default:
					break;
				}
				categorySpinner.setText(categorys[pos]);
			}
		});
	}

	private void showPopWindow() {
		popWindow.setWidth(item_category_spinner_parent.getWidth());
		popWindow.showAsDropDown(item_category_spinner_parent);
	}

	@Override
	protected void onResume() {
		super.onResume();
	};

}
